package com.mini.grpc.examples.helloworld;

import com.mini.grpc.common.StreamObserver;
import java.util.logging.Logger;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * HelloWorld服务的具体实现
 * 演示一元调用、服务端流、客户端流和双向流的完整实现
 */
public class HelloWorldServiceImpl extends HelloWorldServiceGrpc.HelloWorldServiceImplBase {
    
    private static final Logger logger = Logger.getLogger(HelloWorldServiceImpl.class.getName());
    private final AtomicInteger requestCounter = new AtomicInteger(0);
    
    @Override
    public String sayHello(String name) {
        System.out.println("=== HelloWorldServiceImpl.sayHello called with: " + name + " ===");
        int requestId = requestCounter.incrementAndGet();
        logger.info(String.format("[请求#%d] 收到一元调用请求: name=%s", requestId, name));
        
        // 模拟一些处理时间
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.warning("处理被中断");
        }
        
        String response = String.format("Hello, %s! (请求ID: %d)", name, requestId);
        logger.info(String.format("[请求#%d] 返回响应: %s", requestId, response));
        
        return response;
    }
    
    @Override
    public void sayHelloServerStream(String name, StreamObserver<String> responseObserver) {
        int requestId = requestCounter.incrementAndGet();
        logger.info(String.format("[请求#%d] 收到服务端流调用请求: name=%s", requestId, name));
        
        try {
            // 发送5条消息
            for (int i = 1; i <= 5; i++) {
                String message = String.format("Hello %s, 这是第 %d 条消息 (请求ID: %d)", name, i, requestId);
                logger.info(String.format("[请求#%d] 发送流消息 %d: %s", requestId, i, message));
                
                responseObserver.onNext(message);
                
                // 模拟处理延迟
                Thread.sleep(500);
            }
            
            logger.info(String.format("[请求#%d] 服务端流调用完成", requestId));
            responseObserver.onCompleted();
            
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.warning(String.format("[请求#%d] 服务端流调用被中断", requestId));
            responseObserver.onError(new RuntimeException("服务被中断", e));
        } catch (Exception e) {
            logger.severe(String.format("[请求#%d] 服务端流调用发生错误: %s", requestId, e.getMessage()));
            responseObserver.onError(e);
        }
    }
    
    @Override
    public StreamObserver<String> sayHelloClientStream(StreamObserver<String> responseObserver) {
        int requestId = requestCounter.incrementAndGet();
        logger.info(String.format("[请求#%d] 开始客户端流调用", requestId));
        
        return new StreamObserver<String>() {
            private final StringBuilder names = new StringBuilder();
            private int messageCount = 0;
            
            @Override
            public void onNext(String name) {
                messageCount++;
                logger.info(String.format("[请求#%d] 收到客户端流消息 %d: %s", requestId, messageCount, name));
                
                if (names.length() > 0) {
                    names.append(", ");
                }
                names.append(name);
            }
            
            @Override
            public void onError(Throwable t) {
                logger.severe(String.format("[请求#%d] 客户端流发生错误: %s", requestId, t.getMessage()));
                responseObserver.onError(t);
            }
            
            @Override
            public void onCompleted() {
                String finalResponse = String.format("Hello to all %d friends: %s (请求ID: %d)", 
                    messageCount, names.toString(), requestId);
                logger.info(String.format("[请求#%d] 客户端流调用完成，返回: %s", requestId, finalResponse));
                
                responseObserver.onNext(finalResponse);
                responseObserver.onCompleted();
            }
        };
    }
    
    @Override
    public StreamObserver<String> sayHelloBidiStream(StreamObserver<String> responseObserver) {
        int requestId = requestCounter.incrementAndGet();
        logger.info(String.format("[请求#%d] 开始双向流调用", requestId));
        
        return new StreamObserver<String>() {
            private int messageCount = 0;
            
            @Override
            public void onNext(String name) {
                messageCount++;
                String response = String.format("Hello, %s! 这是双向流响应 #%d (请求ID: %d)", 
                    name, messageCount, requestId);
                logger.info(String.format("[请求#%d] 收到双向流消息 %d: %s，立即响应: %s", 
                    requestId, messageCount, name, response));
                
                responseObserver.onNext(response);
            }
            
            @Override
            public void onError(Throwable t) {
                logger.severe(String.format("[请求#%d] 双向流发生错误: %s", requestId, t.getMessage()));
                responseObserver.onError(t);
            }
            
            @Override
            public void onCompleted() {
                logger.info(String.format("[请求#%d] 双向流调用完成，共处理 %d 条消息", requestId, messageCount));
                responseObserver.onCompleted();
            }
        };
    }
} 